<template>
  <div>
    <a-modal
      :title="currTitle()"
      :visible="visible"
      @cancel="showModel(false)"
      width="60%"
    >
      <span class="spanValue">
        <a-card style="width: 50%; display: inline-block">
          <div style="width: 100%" class="ipAddrass">
            <template>
              <div class="table-operator" style="width: 20%; min-width: 400px">
                <a-form :form="form" @submit="handleSubmit">
                  <!--  最大连接数-->
                  <a-form-item v-bind="formItemLayout" label="同时登录数量限制">
                    <a-input
                      v-decorator="[`loginAtTheSameTime`, validatorRules.count]"
                      placeholder="请输入 1 到 100 的整数"
                      style="width: 80%; margin-right: 8px"
                    />
                  </a-form-item>
                  <!--启用IP绑定按钮-->
                  <a-form-item v-bind="formItemLayout" label="IP绑定">
                    <a-switch
                      v-decorator="[
                        `loginIpWhiteListOnOff`,
                        {
                          // 绑定子节点的属性值
                          valuePropName: 'checked',
                          // 给子节点一个默认值
                          initialValue: true,
                        },
                      ]"
                      checked-children="开"
                      un-checked-children="关"
                      @click="btnClicked"
                    />
                  </a-form-item>
                  <!--        IP地址输入列表-->
                  <div v-if="btnChecked">
                    <a-form-item
                      v-for="(k, index) in form.getFieldValue('keys')"
                      :key="k"
                      v-bind="
                        index === 0
                          ? formItemLayout
                          : formItemLayoutWithOutLabel
                      "
                      :label="index === 0 ? 'IP地址绑定' : ''"
                      :required="false"
                    >
                      <a-input
                        v-decorator="[
                          `loginIpWhiteList[${k}]`,
                          validatorRules.ip,
                        ]"
                        placeholder="请输入需要绑定的IP地址"
                        style="width: 80%; margin-right: 8px"
                      />
                      <a-icon
                        class="dynamic-delete-button"
                        type="minus-circle-o"
                        @click="() => remove(k)"
                      />
                    </a-form-item>
                    <a-form-item v-bind="formItemLayoutWithOutLabel">
                      <a-button type="dashed" style="width: 80%" @click="add">
                        <a-icon type="plus" /> 添加绑定输入项
                      </a-button>
                    </a-form-item>
                  </div>
                </a-form>
              </div>
            </template>
          </div>
          <div style="width: 100%" class="ipButton">
            <a-button
              type="primary"
              @click="handleSubmitIp"
              style="float: right"
              >提交</a-button
            >
          </div>
        </a-card>
      </span>
      <span class="spanValue">
        <a-card style="width: 50%; display: inline-block; vertical-align: top">
          <div style="width: 100%" class="ipAddrass">
            <template>
              <div class="table-operator" style="width: 20%; min-width: 400px">
                <a-form :form="form" @submit="handleSubmit">
                  <a-form-item v-bind="formItemLayout" label="">
                    <div style="height: 40px"></div>
                  </a-form-item>
                  <a-form-item v-bind="formItemLayout" label="时间段禁用">
                    <a-switch
                      v-decorator="[
                        `disableLoginTimeOnOff`,
                        {
                          // 绑定子节点的属性值
                          valuePropName: 'checked',
                          // 给子节点一个默认值
                          initialValue: true,
                        },
                      ]"
                      checked-children="开"
                      un-checked-children="关"
                      @click="timeClicked"
                    />
                  </a-form-item>
                  <!-- 禁用时间段 -->
                  <div v-if="timeChecked">
                    <a-col :md="24" :sm="24">
                      <a-form-item
                        label="开始禁用时间:"
                        :labelCol="{ span: 8 }"
                        :wrapperCol="{ span: 9, offset: 0 }"
                      >
                        <a-date-picker
                          v-decorator="['limitTheLoginStartTime',validatorRules.time]"
                          :disabled-date="disabledStartDate"
                          show-time
                          :allowClear="false"
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择开始禁用时间"
                          @openChange="handleStartOpenChange"
                        />
                      </a-form-item>
                    </a-col>

                    <a-col :md="24" :sm="24">
                      <a-form-item
                        label="结束禁用时间:"
                        :labelCol="{ span: 8 }"
                        :wrapperCol="{ span: 9, offset: 0 }"
                      >
                        <a-date-picker
                          v-decorator="['limitTheLoginEndTime']"
                          :disabled-date="disabledEndDate"
                          show-time
                          :allowClear="false"
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择结束禁用时间"
                          @openChange="handleEndOpenChange"
                        />
                      </a-form-item>
                    </a-col>
                  </div>
                </a-form>
              </div>
            </template>
          </div>
          <div style="width: 100%">
            <a-button
              type="primary"
              @click="handleSubmitTime"
              style="float: right"
              >提交</a-button
            >
          </div>
        </a-card>
      </span>
      <template slot="footer">
        <a-button @click="showModel(false)">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction } from "@/api/manage";
import moment from "moment";

let id = 0;
export default {
  name: "UserLoginConfigModal",
  data() {
    return {
      startValue: "",
      endValue: "",
      userName: "",
      userID: "",
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 16, offset: 8 },
        },
      },
      validatorRules: {
        count: {
          validateTrigger: ["change", "blur"],
          rules: [
            {
              required: true,
              whitespace: true,
              pattern: /^([1-9][0-9]{0,1}|100)$/,
              message: "请输入1-100的整数!",
            },
          ],
        },
        time: {
          validateTrigger: ["change", "blur"],
          rules: [
            {
              required: true,
              message: "请输入开始禁用时间!",
            },
          ],
        },
        ip: {
          validateTrigger: ["change", "blur"],
          rules: [
            {
              required: true,
              whitespace: true,
              // pattern:/^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/,
              pattern:
                /^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/,
              message: "请输入正确的IP地址 或 删除此项!",
            },
          ],
        },
      },
      btnChecked: true,
      timeChecked: true,
      ipList: [],
      url: {
        getParam: "/sys/user/user-login-config",
        setParam: "/sys/user/save-login-ip-config",
        getParams: "/sys/user/save-disable-login-time-config",
      },
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "sys_param_set" });
    this.form.getFieldDecorator("keys", { initialValue: [], preserve: true });
  },
  mounted() {
    console.log("---------------------------------------");
  },
  methods: {
    currTitle() {
      let str = "[ " + this.userName + " ]的登录配置";
      return str;
    },
    showModel(visible) {
      this.visible = visible;
      if (this.userID.length !== 0) {
        this.getData();
      }
    },
    getData() {
      this.clearViewData();
      let that = this;

      // 获取数据
      getAction(that.url.getParam + "/" + this.userID).then((res) => {
        if (res.code === "00000") {
          console.log(res, "url.getParam");

          //ip地址=========>
          for (let i = 0; i < res.data.loginIpWhiteList.length; i++) {
            this.add();
          }
          this.btnChecked = true;
          if (res.data.loginIpWhiteListOnOff === "off") {
            this.btnChecked = false;
          }
          this.form.setFieldsValue({
            loginAtTheSameTime: res.data.loginAtTheSameTime,
            loginIpWhiteListOnOff: this.btnChecked,
          });
          that.ipList = res.data.loginIpWhiteList;

          //禁用时间=======>
          this.timeChecked = true;
          if (
            res.data.disableLoginTimeOnOff === "off" ||
            res.data.disableLoginTimeOnOff == null
          ) {
            this.timeChecked = false;
          }
          this.form.setFieldsValue({
            disableLoginTimeOnOff: this.timeChecked,
          });

          //开始结束时间为空时判断========>
          if (
            res.data.limitTheLoginStartTime == "null" ||
            res.data.limitTheLoginStartTime == "Invalid date"
          ) {
            that.startTime = null;
          } else {
            that.startTime = res.data.limitTheLoginStartTime;
          }

          if (
            res.data.limitTheLoginEndTime == "null" ||
            res.data.limitTheLoginEndTime == "Invalid date"
          ) {
            that.endTime = null;
          } else {
            that.endTime = res.data.limitTheLoginEndTime;
          }


          // 开启ip绑定
          if (this.btnChecked) {
            this.$nextTick(() => {
              this.form.setFieldsValue({
                loginIpWhiteList: that.ipList,
              });
            });
          }

          // 开始禁用时间
          if (this.timeChecked) {
            this.$nextTick(() => {
              this.form.setFieldsValue({
                limitTheLoginStartTime: that.startTime,
                limitTheLoginEndTime: that.endTime,
              });
            });
          }
        } else {
          that.$message.warning("获取系统参数:" + res.msg);
          that.ipList = [];
          that.startTime = "";
        }
      });
    },

    setUserID(userid, username) {
      this.userID = userid;
      this.userName = username;
    },
    remove(k) {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue("keys");

      // can use data-binding to set
      form.setFieldsValue({
        keys: keys.filter((key) => key !== k),
      });
    },
    clearViewData() {
      id = 0;
      this.form.setFieldsValue({
        keys: [],
        loginIpWhiteList: [],
      });
    },
    add() {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue("keys");
      const nextKeys = keys.concat(id++);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    },
    // 开始结束时间
    disabledStartDate(startValue) {
      console.log(startValue);
      // return startValue && startValue < moment().subtract(1,'days').endOf("day");
    },
    disabledEndDate(endValue){
      console.log(endValue);
    },
    // handleSubmit() {
    //   let that = this;
    //   this.form.validateFields((err, values) => {
    //     if (!err) {
    //       // const { keys, names } = values;
    //       console.log("Received values of form: ", values);
    //       if (values.keys) {
    //         delete values.keys;
    //       }
    //       if (!("loginIpWhiteList" in values)) {
    //         values.loginIpWhiteList = this.ipList;
    //       }
    //       values.loginAtTheSameTime = Number(values.loginAtTheSameTime);
    //       values.loginIpWhiteListOnOff = that.btnChecked ? "on" : "off";
    //       values.userId = this.userID;

    //       // 判断是否开启ip绑定
    //       // if (values.loginIpWhiteListOnOff == "on") {
    //         // 开始、结束时间格式转换以及判断
    //         // if (values.limitTheLoginEndTime == null) {
    //         //   values.limitTheLoginEndTime = null;
    //         // } else {
    //         //   values.limitTheLoginEndTime = moment(
    //         //     values.limitTheLoginEndTime
    //         //   ).format("YYYY-MM-DD HH:mm:ss");
    //         // }

    //         // if (values.limitTheLoginStartTime == null) {
    //         //   values.limitTheLoginStartTime = null;
    //         // } else {
    //         //   values.limitTheLoginStartTime = moment(
    //         //     values.limitTheLoginStartTime
    //         //   ).format("YYYY-MM-DD HH:mm:ss");
    //         // }

    //         // 开始 与 结束 时间都为空时
    //         // if (
    //         //   values.limitTheLoginEndTime == null &&
    //         //   values.limitTheLoginStartTime == null
    //         // ) {
    //         //   this.$message.warning("请选择禁用开始或者结束时间");
    //         //   return;
    //         // } else if (
    //         //   values.limitTheLoginEndTime !== null &&
    //         //   values.limitTheLoginStartTime !== null
    //         // ) {
    //         //   //开始 结束 时间判断
    //         //   let startValueTime = values.limitTheLoginStartTime;
    //         //   let endValueTime = values.limitTheLoginEndTime;
    //         //   console.log(startValueTime, endValueTime, "开始时间结束时间");
    //         //   let start = startValueTime.replace(/-/g, "");
    //         //   let starts = start.replace(/:/g, "");
    //         //   let startes = starts.replace(/ /g, "");
    //         //   console.log(startes);
    //         //   let end = endValueTime.replace(/-/g, "");
    //         //   let ends = end.replace(/:/g, "");
    //         //   let endes = ends.replace(/ /g, "");
    //         //   console.log(endes);

    //         //   if (startes > endes) {
    //         //     this.$message.warning("开始时间应早于结束时间！");
    //         //     return;
    //         //   }
    //         // }
    //       // }

    //       // 判断是否开启时间段禁用

    //       console.log("values of form: ", values);
    //       // postAction(this.url.setParam, values).then((res) => {
    //       //   if (res.code == "00000") {
    //       //     that.$message.success("系统参数设置成功");
    //       //     that.ipList = values.loginIpWhiteList;
    //       //   } else {
    //       //     that.$message.warning("系统参数设置失败:" + res.msg);
    //       //   }
    //       // });
    //     }
    //   });
    // },

    // ip绑定提交
    handleSubmitIp() {
      let that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          if (values.keys) {
            delete values.keys;
          }
          if (!("loginIpWhiteList" in values)) {
            values.loginIpWhiteList = this.ipList;
          }
          values.loginAtTheSameTime = Number(values.loginAtTheSameTime);
          values.loginIpWhiteListOnOff = that.btnChecked ? "on" : "off";
          values.userId = this.userID;

          const params = {};
          params.loginAtTheSameTime = values.loginAtTheSameTime;
          params.loginIpWhiteListOnOff = values.loginIpWhiteListOnOff;
          params.userId = values.userId;
          params.loginIpWhiteList = values.loginIpWhiteList;

          console.log("values of form: ", params);
          postAction(this.url.setParam, params).then((res) => {
            if (res.code == "00000") {
              that.$message.success("系统参数设置成功");
              that.ipList = values.loginIpWhiteList;
              // this.showModel(false);
            } else {
              that.$message.warning("系统参数设置失败:" + res.msg);
              // this.showModel(false);
            }
          });
        }
      });
    },
    // 禁用时间提交
    handleSubmitTime() {
      console.log(this.form, "formValue");
      let that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          values.disableLoginTimeOnOff = that.timeChecked ? "on" : "off";
          values.userId = this.userID;

          //  判断是否开启ip绑定
          if (values.disableLoginTimeOnOff == "on") {
            // 开始、结束时间格式转换以及判断
            if (values.limitTheLoginEndTime == null) {
              values.limitTheLoginEndTime = null;
            } else {
              values.limitTheLoginEndTime = moment(
                values.limitTheLoginEndTime
              ).format("YYYY-MM-DD HH:mm:ss");
            }

            if (values.limitTheLoginStartTime == null) {
              this.$message.warning("请选择开始时间");
              return;
            } else {
              values.limitTheLoginStartTime = moment(
                values.limitTheLoginStartTime
              ).format("YYYY-MM-DD HH:mm:ss");
            }

            // 开始 与 结束 时间都为空时
            if (
              values.limitTheLoginEndTime == null &&
              values.limitTheLoginStartTime == null
            ) {
              this.$message.warning("请选择开始时间或者结束时间");
              return;
            } else if (
              values.limitTheLoginEndTime !== null &&
              values.limitTheLoginStartTime !== null
            ) {
              //开始 结束 时间判断
              let startValueTime = values.limitTheLoginStartTime;
              let endValueTime = values.limitTheLoginEndTime;
              console.log(startValueTime, endValueTime, "开始时间结束时间");
              let start = startValueTime.replace(/-/g, "");
              let starts = start.replace(/:/g, "");
              let startes = starts.replace(/ /g, "");
              console.log(startes);
              let end = endValueTime.replace(/-/g, "");
              let ends = end.replace(/:/g, "");
              let endes = ends.replace(/ /g, "");
              console.log(endes);

              if (startes > endes) {
                this.$message.warning("开始时间应早于结束时间！");
                return;
              }
            }
          }

          const param = {};
          param.disableLoginTimeOnOff = values.disableLoginTimeOnOff;
          param.userId = values.userId;
          param.limitTheLoginStartTime = values.limitTheLoginStartTime;
          param.limitTheLoginEndTime = values.limitTheLoginEndTime;

          console.log("values of form: ", param);
          postAction(this.url.getParams, param).then((res) => {
            if (res.code == "00000") {
              that.$message.success("系统参数设置成功");
              // this.showModel(false);
            } else {
              that.$message.warning("系统参数设置失败:" + res.msg);
              // this.showModel(false);
            }
          });
        }
      });
    },
    validateIp() {
      return false;
    },
    // ip地址
    btnClicked(checked) {
      this.btnChecked = checked;
      if (this.btnChecked) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            loginIpWhiteList: this.ipList,
          });
        });
      }
    },

    // 时间禁用
    timeClicked(checked) {
      console.log('时间禁用',checked)
      this.timeChecked = checked;
      if (this.timeChecked) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            limitTheLoginStartTime: this.startTime,
            limitTheLoginEndTime: this.endTime,
          });
        });
      }
    },
  },
};
</script>
<style lang="less" scoped>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.spanValue .ant-card-body {
  height: 460px;
}

/deep/.ant-modal-body {
  padding: 0px !important;
}

.ipAddrass {
  height: 400px;
  overflow-y: scroll;
  scrollbar-width: none;
}
.ipButton {
  bottom: 0;
}
</style>